//
//  AudioBookPlayViewController.m
//  FunRead
//
//  Created by  King on 15/5/28.
//  Copyright (c) 2015年 华东伟. All rights reserved.
//

#import "AudioBookPlayViewController.h"
#import "AudioStreamer.h"
#import "AudioBookPlayModel.h"
#import "SANetWorkingTask.h"
#import <SDWebImage/UIImageView+WebCache.h>

#import <MediaPlayer/MPNowPlayingInfoCenter.h>
#import <MediaPlayer/MPMediaItem.h>
#import <AVFoundation/AVFoundation.h>
@interface AudioBookPlayViewController ()
// 存放网络请求信息的可变array
@property (nonatomic, retain) NSMutableArray *modelArray;
@property (nonatomic, retain) UIButton *playButton;
@property (nonatomic, retain) AudioStreamer *audio;

@property (nonatomic, retain) UIProgressView *progress;// 播放进度
@property (nonatomic, retain) UILabel *minuteLabel; // 控制显示时间
@property (nonatomic, retain) UILabel *secondLabel; // 控制显示时间
@property (nonatomic, assign) int aMinute;//分
@property (nonatomic, assign) NSTimer *time;
@end

@implementation AudioBookPlayViewController
- (void)dealloc
{
    [_trackId release];
    [_name release];
    [_modelArray release];
    [_URLArray release];
    [_audio release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.URLArray = [NSMutableArray array];
        self.modelArray = [NSMutableArray array];
        self.audio = [AudioStreamer shareManager];
    }
    return self;
}
#pragma mark - 播放单例
static AudioBookPlayViewController *single = nil;
+ (AudioBookPlayViewController *)playInterface
{
    //单例安全
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        if (!single) {
            single = [[AudioBookPlayViewController alloc]init];
        }
    });
    return single;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 添加背景图片
    UIImageView *BackImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    BackImage.image = [UIImage imageNamed:@"1.jpg"];
    [self.view addSubview:BackImage];
    [BackImage release];
    // 设置导航返回键图片
    UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"backbefore.png"] style:UIBarButtonItemStylePlain target:self action:@selector(action:)];
    self.navigationItem.leftBarButtonItem = button;
    [button release];
    
    self.navigationItem.title = self.name;
    [self createPlayView];
    
}
- (void)action:(id)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 网络请求
//- (void)startConnection
//{
//    __block AudioBookPlayViewController *play = self;
//    NSString *str = [NSString stringWithFormat:@"http://app.9nali.com/961/tracks/%@?device=iPad&version=1.1.2", self.trackId];
//    [SANetWorkingTask request:str parmater:nil block:^(NSDictionary *result) {
//        AudioBookPlayModel *playModel = [[AudioBookPlayModel alloc] init];
//        [playModel setValuesForKeysWithDictionary:result];
//        [play.modelArray addObject:playModel];
//        [playModel release];
//
//        [self play];
//    }];
//}
#pragma mark - playView页面
- (void)createPlayView
{
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [backImage sd_setImageWithURL:[NSURL URLWithString:self.playImage] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    [self.view addSubview:backImage];
    [backImage release];
    
    self.playButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 10 , self.view.frame.size.width / 10)];
    [_playButton setCenter:CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 7 * 5)];
    [_playButton setImage:[UIImage imageNamed:@"pausebutton.png"] forState:UIControlStateNormal];
    [_playButton addTarget:self action:@selector(playButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playButton];
    [_playButton release];
    
    UIButton *next = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [next setCenter:CGPointMake(self.view.frame.size.width / 3 * 2, self.view.frame.size.height / 7 * 5)];
    [next setBackgroundImage:[UIImage imageNamed:@"next.png"] forState:UIControlStateNormal];
    [next addTarget:self action:@selector(nextSongButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:next];
    
    UIButton *before = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [before setCenter:CGPointMake(self.view.frame.size.width / 3, self.view.frame.size.height / 7 * 5)];
    [before setImage:[UIImage imageNamed:@"before.png"] forState:UIControlStateNormal];
    [before addTarget:self action:@selector(beforeSongButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:before];
    
    // 播放器进度条
    self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
    [self.progress setCenter:CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 3 * 2)];
    [self.view addSubview:_progress];
    [_progress release];

}
// Play按钮事件
- (void)playButton:(id)sender
{
    if ([self.audio isPlaying]) {
        
        [self.playButton setImage:[UIImage imageNamed:@"playbutton.png"] forState:UIControlStateNormal];
        
        [self.audio pause];
    }
    else if([self.audio isPaused]) {
        [self.audio pause];
        
        [self.playButton setImage:[UIImage imageNamed:@"pausebutton.png"] forState:UIControlStateNormal];
    }
    else if (![self.audio isPlaying]) {
        NSURL *url = [NSURL URLWithString:self.URLArray[self.page]];
        [self.audio initWithURL:url];
        [self.audio start];
        [self.playButton setImage:[UIImage imageNamed:@"pausebutton.png"] forState:UIControlStateNormal];
    }
}
// 进入当前页面播放

- (void)play
{
    [self.audio stop];
    NSURL *url = [NSURL URLWithString:self.URLArray[self.page]];
    [self.audio initWithURL:url];
    [self.audio start];
    //每0.1秒刷新一次progress，对事件进行监听
    self.time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playProgress) userInfo:nil repeats:YES];

}
// 下一首按钮点击事件
- (void)nextSongButton:(id)next
{
    self.page++;
    [self.audio stop];
    if (_page < [_URLArray count]) {
        self.navigationItem.title = self.titleArray[self.page];
        NSURL *url = [NSURL URLWithString:self.URLArray[self.page]];
        [self.audio initWithURL:url];
    }
    if (_page == [_URLArray count])
    {
        self.page = 0;
        self.navigationItem.title = self.titleArray[self.page];
        NSURL *url = [NSURL URLWithString:self.URLArray[self.page]];
        [self.audio initWithURL:url];
    }
    [self.playButton setImage:[UIImage imageNamed:@"pausebutton.png"] forState:UIControlStateNormal];
    [self.audio start];
}
// 上一曲按钮点击事件
- (void)beforeSongButton:(id)before
{
    self.page--;
    [self.audio stop];
    if (_page >= 0) {
        self.navigationItem.title = self.titleArray[self.page];
        NSURL *url = [NSURL URLWithString:self.URLArray[self.page]];
        [self.audio initWithURL:url];
    }
    if (_page < 0)
    {
        self.page = [_URLArray count] - 1;
        self.navigationItem.title = self.titleArray[self.page];
        NSURL *url = [NSURL URLWithString:self.URLArray[self.page]];
        [self.audio initWithURL:url];
    }
    [self.audio start];
}
// 播放器进度条
- (void)playProgress
{
    //  判断当前播放状态
    if ([self.audio isWaiting]) {
        NSLog(@"正在缓冲");
    }
    if ([self.audio isPaused]) {

    }
    if ([self.audio isIdle]) {
        NSLog(@"停止播放");
    }
    
    
    float minute = (self.audio.duration - self.audio.progress) / 60;
    float second = ((self.audio.duration - self.audio.progress) / 60 - self.aMinute) * 60 ;
    
    if (second == 0) {
        
        self.aMinute = (int)minute;
        self.aMinute = self.aMinute - 6;
        NSString *minuteTime = [NSString stringWithFormat:@"%d",self.aMinute];
        self.minuteLabel.text = minuteTime;
    }
    NSString *secondTime = [NSString stringWithFormat:@"%.f",second];
    
    self.secondLabel.text = secondTime;

    // 播放器进度条属性 = 当前播放时间/ 总时间;
    _progress.progress = self.audio.progress /self.audio.duration;
}

@end
